$(window).addEvent('domready', function() {
  var nodes = $$('.report_download');
  if(nodes.length)
  {
    nodes.addEvent('click', reportDownload);
  }
});

function attachDownloadReportListeners()
{
  var nodes = $$('.report_download');
  if(nodes.length)
  {
    nodes.removeEvents('click');
    nodes.addEvent('click', reportDownload);
  }
}

function removeDownloadReportListeners()
{
  var nodes = $$('.report_download');
  if(nodes.length)
  {
    nodes.removeEvents('click');
    nodes.addEvent('click', function() { return false; });
  }
}

function reportDownload(e)
{
  removeDownloadReportListeners();

  var node = {}, data = {};

  node['loader'] = new Image();
  node['loader'].src = 'http://' + location.host + '/images/site/front/fbloader.gif';
  node['loader'].className = 'loader';
  node['loader'].inject(e.target, 'after');

  data['download_id'] = e.target.getAttribute('data-download-id');

  new Request.JSON({url: 'http://' + location.host + '/report/download/' + data['download_id'], onSuccess: downloadReportCheckResponse.bind(e.target), onFailure: downloadReportCheckFailed.bind(e.target)}).get();

  return false;
}

function downloadReportCheckResponse(response, result)
{
  var node = {};

  node['loader'] = this.getNext('img');
  if(node['loader'])
  {
    node['loader'].destroy();
  }

  if(response['reported'])
  {
    if(response['logged_in'])
    {
      var light = new LightFace({title: 'Add Download Report',
                                 keys: { esc: function () { attachDownloadReportListeners(); this.destroy(); }}});

      node['content'] = $('dialog_9').clone();
      node['content'].inject(light.messageBox);

      light.addButton('Close', function() { attachDownloadReportListeners(); light.destroy(); }, true)

      light.open();
    }
    else
    {
      var light = new LightFace({title: 'Add Download Report',
                                 keys: { esc: function () { attachDownloadReportListeners(); this.destroy(); }}});

      node['content'] = $('dialog_10').clone();
      node['content'].getElement('span.ip').innerHTML = response['ip'];
      node['content'].inject(light.messageBox);

      light.addButton('Close', function() { attachDownloadReportListeners(); light.destroy(); }, true)

      light.open();
    }
  }
  else
  {
    if(response['logged_in'])
    {
      var light = new LightFace({title: 'Report Download',
                                 keys: { esc: function () { attachDownloadReportListeners(); this.destroy(); }}});

      node['content'] = $('dialog_7').getElement('form').clone();
      node['content'].action += ('/' + this.getAttribute('data-download-id'));
      node['content'].addEvent('submit', submitDownloadReport.bind(light));
      node['content'].inject(light.messageBox);

      light.addButton('Submit', submitDownloadReport, 'blue');
      light.addButton('Close', function() { attachDownloadReportListeners(); light.destroy(); }, true)

      light.open();
    }
    else
    {
      var light = new LightFace({title: 'Report Download',
                                 keys: { esc: function () { attachDownloadReportListeners(); this.destroy(); }}});

      node['content'] = $('dialog_8').getElement('form').clone();
      node['content'].action += ('/' + this.getAttribute('data-download-id'));
      node['content'].addEvent('submit', submitDownloadReport.bind(light));
      node['content'].inject(light.messageBox);

      node['captcha'] = new Image();
      node['captcha'].src = 'http://' + location.host + '/captcha/default/' + Date.now();
      node['captcha'].inject(light.messageBox.getElement('.line.antispam'));

      light.addButton('Submit', submitDownloadReport, 'blue');
      light.addButton('Close', function() { attachDownloadReportListeners(); light.destroy(); }, true)

      light.open();
    }
  }
}

function downloadReportCheckFailed(xhr)
{
  var node = {};

  node['loader'] = this.getNext('img');
  if(node['loader'])
  {
    node['loader'].destroy();
  }

  attachDownloadReportListeners();
}

function submitDownloadReport()
{
  this.fade();

  var form = $(this.messageBox).getElement('form');
  var error_box = form.getElement('.line');
  error_box.innerHTML = '';

  var params = form.toQueryString().parseQueryString();

  new Request.JSON({url: form.getAttribute('action'), onSuccess: addDownloadReportResponse.bind(this), onFailure: addDownloadReportFailed.bind(this)}).post(params);

  return false;
}

function addDownloadReportResponse(response, result)
{
  if(response['error'])
  {
    var form = $(this.messageBox).getElement('form');
    var error_box = form.getElement('.line');
    var errors = 'Please correct the following errors and resubmit the form.';
    errors += '<ul class="error_list">';
    for(var i = 0; i < response['errors'].length; i++)
    {
      errors += '<li>' + response['errors'][i] + '</li>';
    }
    errors += '</ul>';
    error_box.innerHTML = errors;
    this.unfade();
  }
  else
  {
    $(this.messageBox).getElement('form').destroy();
    var heading = new Element('h3.generic', {'html': 'Download Reported!'});
    var message = new Element('div.prompt',
                              {'html': 'Thank you for reporting this download. We\'ll attend to it as soon as possible.'});

    heading.inject(this.messageBox);
    message.inject(this.messageBox);

    this.removeButton('Submit');

    this.unfade();
  }
}

function addDownloadReportFailed(xhr)
{
  var form = $(this.messageBox).getElement('form');
  var error_box = form.getElement('.line');
  var errors = 'Please correct the following errors and resubmit the form.';
  errors += '<ul class="error_list">';
  errors += '<li>' + 'Unable to access add download report web page' + '</li>';
  errors += '</ul>';
  error_box.innerHTML = errors;
  this.unfade();
}
